import Vue from 'vue'
import Vuex from 'vuex'
import socket from '@/socket'
import { Notification } from 'element-ui'

Vue.use(Vuex)

const state = {
  connected: false, // 当前连接状态
  nickname: '', // 当前用户昵称
  users: [], // 房间用户昵称列表
  holder: '', // 游戏主持人
  lines: [], // 绘图信息（本质是线条的集合） 
}

const getters = {
  isGameStarted(state) {
    // 根据主持人是否存在，判断游戏是否开始
    return !!state.holder
  }
}

const mutations = {
  // 更新连接状态
  updateConnected(state, connected) {
    state.connected = connected
  },
  // 更新昵称
  updateNickname(state, nickname) {
    state.nickname = nickname
  },
  // 更新玩家列表
  updateUserList(state, users) {
    state.users = users || []
  },
  // 更新主持人
  updateHolder(state, holder) {
    state.holder = holder
  },
  // 添加用户进玩家列表
  addUserToList(state, nickname) {
    if (!state.users.includes(nickname)) {
      state.users.push(nickname)
      Notification({title: '系统消息', message: `欢迎玩家${nickname} 进入房间！`, iconClass:'el-icon-bell'})
    }
  },
  // 移除已离开的用户
  delUserFromList(state, nickname) {
    if (!!nickname) {
      state.users = state.users.filter(item => item !== nickname)
      Notification({title: '系统消息', message: `玩家${nickname} 离开了房间！`, iconClass:'el-icon-bell'})
    }
  },
  // 添加新线条
  drawNewLine(state, newLine) {
    state.lines.push(newLine)
  },
  // 更新线条
  updateLine(state, lastLine) {
    let line = state.lines[state.lines.length - 1]
    line.points = lastLine.points
  }
}

const actions = {
  // 校验昵称是否存在
  checkUserExist(context, nickName) {
    return new Promise((resolve, reject) => {
      socket.emit('checkUserExist', nickName, (isExist) => {
        resolve(isExist)
      })
    })
  },
  // 自己进入房间
  enterRoom({ commit }) {
    let nickname = localStorage.getItem('nickname')
    socket.emit('enterRoom', nickname)
    commit('updateNickname', nickname)
    commit('updateConnected', true)
  },
  // 离开游戏
  exitGame({ commit }) {
    socket.emit('exitGame')
    commit('updateNickname', '')
    localStorage.removeItem('nickname')
  },
  // 告知服务器开始画新线
  sendDrawNewLine(context, newLine) {
    socket.emit('newLine', newLine)
  },
  // 告知服务器开始更新画线
  sendUpdateNewLine(context, lastLine) {
    socket.emit('updateLine', lastLine)
  }
}

const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

export default store;